--[[
    双端列表
--]]


local List = {}

function List.new(...)
    local instance = setmetatable({}, {__index=List})
    instance:ctor(...)
    return instance
end

function List:ctor()
    self.first = 0 --左边标记
    self.last = -1 --右边标记
    self.data = {} --用于存放数据
end


function List:pushL(value)
    local first = self.first - 1
    self.data[first] = value
    self.first = first
end

function List:pushR(value)
    local last = self.last + 1
    self.data[last] = value
    self.last = last
end

function List:popL()
    if self.first > self.last then
        --表为空了
        return
    end
    local value = self.data[self.first]
    self.data[self.first] = nil
    self.first = self.first + 1
    return value
end

function List:popR()
    if self.first > self.last then
        --表为空了
        return
    end
    local value = self.data[self.last]
    self.data[self.last] = nil
    self.last = self.last - 1
    return value
end

function List:getData()
    return self.data
end

function List:print()
    for i = self.first, self.last do
        print(i, self.data[i])
    end
end


------------------------------------------------------------------
--测试
------------------------------------------------------------------

if arg and arg[0] == "list.lua" then

    local list = List.new()
    list:pushL(1)
    list:pushL(2)
    list:pushL(3)

    list:pushR(4)
    list:pushR(5)

    list:print()
    print("_______")

    list:popL()
    list:popR()

    list:print()

end

return List